package org.jeecg.modules.tencent_esign.tencent_contract.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.essbasic.v20210526.EssbasicClient;
import com.tencentcloudapi.essbasic.v20210526.models.*;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;

import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.health_records.assess_special.controller.AssessSpecialInfoController;
import org.jeecg.modules.health_records.assess_special.entity.AssessSpecialInfo;
import org.jeecg.modules.health_records.health_record.controller.HealthRecordInfoController;
import org.jeecg.modules.health_records.health_record.entity.HealthRecordInfo;
import org.jeecg.modules.nurse_hospital.entity.NurseHospital;
import org.jeecg.modules.nurse_hospital.service.INurseHospitalService;

import org.jeecg.modules.nurse_user.entity.NurseUser;
import org.jeecg.modules.nurse_user.service.INurseUserService;
import org.jeecg.modules.nurseuser_profile.service.INurseuserProfileService;
import org.jeecg.modules.system.entity.SysTenant;
import org.jeecg.modules.tencent_esign.config.Config;
import org.jeecg.modules.tencent_esign.tencent_consoleloginurl.entity.TencentConsoleloginurlInfo;
import org.jeecg.modules.tencent_esign.tencent_consoleloginurl.service.ITencentConsoleloginurlInfoService;
import org.jeecg.modules.tencent_esign.tencent_contract.entity.CreateFlowDTO;
import org.jeecg.modules.tencent_esign.tencent_contract.entity.TemplateInfoDTO;
import org.jeecg.modules.tencent_esign.tencent_contract.entity.TencentContractInfo;
import org.jeecg.modules.tencent_esign.tencent_contract.entity.TencentStaffcallbackDTO;
import org.jeecg.modules.tencent_esign.tencent_contract.mapper.TencentContractInfoMapper;
import org.jeecg.modules.tencent_esign.tencent_contract.service.ITencentContractInfoService;
import org.jeecg.modules.tencent_esign.tencent_flowsfile.service.ITencentFlowsFileService;
import org.jeecg.modules.tencent_esign.tencent_flowstatuscallback.entity.TencentFlowstatuscallbackDTO;
import org.jeecg.modules.tencent_esign.tencent_flowstatuscallback.entity.TencentFlowstatuscallbackInfo;
import org.jeecg.modules.tencent_esign.tencent_flowstatuscallback.service.ITencentFlowstatuscallbackInfoService;
import org.jeecg.modules.tencent_esign.tencent_forwardflowcallback.entity.TencentForwardflowcallbackInfo;
import org.jeecg.modules.tencent_esign.tencent_forwardflowcallback.service.ITencentForwardflowcallbackInfoService;
import org.jeecg.modules.tencent_esign.tencent_operate.entity.TencentOperateInfo;
import org.jeecg.modules.tencent_esign.tencent_operate.service.ITencentOperateInfoService;
import org.jeecg.modules.tencent_esign.tencent_sign.entity.TencentSignInfo;
import org.jeecg.modules.tencent_esign.tencent_sign.service.ITencentSignInfoService;
import org.jeecg.modules.tencent_esign.tencent_staffcallback.entity.TencentStaffcallbackInfo;
import org.jeecg.modules.tencent_esign.tencent_staffcallback.service.ITencentStaffcallbackInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Description: 电子签合同记录表
 * @Author: jeecg-boot
 * @Date:   2025-07-10
 * @Version: V1.0
 */
@Service
public class TencentContractInfoServiceImpl extends ServiceImpl<TencentContractInfoMapper, TencentContractInfo> implements ITencentContractInfoService {
    @Value("${tencent.esign.secret-key}")
    private String secretKey;
    @Value("${tencent.esign.secret-id}")
    private String secretId;

    @Value("${tencent.esign.endpoint}")
    private String endpoint;
    @Value("${tencent.esign.region}")
    private String region;
    @Value("${tencent.esign.sdk-app-id}")
    private String appId;
    @Value("${tencent.esign.download.enabled}")
    private Boolean downloadEnabled;
    @Value("${tencent.esign.keyCallBack}")
    private String  keyCallBack;
    private String ProxyOrganizationName = "";
    private String Mobile = "";

    @Autowired
    TencentContractInfoMapper tencentContractInfoMapper;

    @Autowired
    ITencentFlowsFileService tencentFlowsFileService;

    @Autowired
    INurseUserService nurseUserService;

    //调用腾讯电子签创建签署流程CreateFlowsByTemplates接口
    @Override
    public  Result<String> createFlowByTemplate(CreateFlowDTO createFlowDTO) {
        try {
            // 1. 初始化客户端
            EssbasicClient client = getInitClient();
            // 2. 构造请求参数
            CreateFlowsByTemplatesRequest req = buildRequestParams(createFlowDTO);
            // 3. 发送请求并获取响应
            CreateFlowsByTemplatesResponse resp = client.CreateFlowsByTemplates(req);
            if(!"".equals(resp.getErrorMessages()[0])){
                System.out.println("合同创建失败："+resp.getErrorMessages()[0]);
                return Result.ok(("合同创建失败："+resp.getErrorMessages()[0]));
            }
            // 4. 处理响应结果
            System.out.println("创建签署流程成功，响应数据:");
            System.out.println(CreateFlowsByTemplatesResponse.toJsonString(resp));
            // 打印流程ID和签署链接
            if (resp.getFlowIds() != null && resp.getFlowIds().length > 0) {
                System.out.println("\n创建的流程ID:");
                Arrays.stream(resp.getFlowIds()).forEach(System.out::println);

            }

            //本地记录合同签署信息和操作记录
            TencentContractInfo contractInfo=new TencentContractInfo ();//合同记录信息
            TencentSignInfo signInfo=new TencentSignInfo (); //签署方信息
            TencentOperateInfo  operateInfo=new TencentOperateInfo();//接口调用信息
            //合同记录信息
            contractInfo.setFlowid(resp.getFlowIds()[0]);
            contractInfo.setConTitle(createFlowDTO.getFlowName());
            contractInfo.setConType("");
            contractInfo.setConStatus("签署");

            contractInfo.setCreateBy(createFlowDTO.getOperatorId());
            contractInfo.setCreateTime(new Date());
            contractInfo.setNote("");
            // //签署方信息（个人）
            FlowApproverInfo personApprover =new FlowApproverInfo();
            if(createFlowDTO.getSigners()!=null&&!createFlowDTO.getSigners().isEmpty()){
                personApprover =convertSigners(createFlowDTO.getSigners());
                signInfo.setSignId(resp.getRequestId());
                signInfo.setConId(resp.getFlowIds()[0]);
                signInfo.setSignName(personApprover.getName());
                signInfo.setIdType(personApprover.getIdCardType());
                signInfo.setIdNumber(personApprover.getIdCardNumber());
                signInfo.setTel(personApprover.getMobile());
                /*signInfo.setEmail();
                signInfo.setSignOrder();
                signInfo.setSignStatus();
                signInfo.setSignDate();
                signInfo.setSignIp();
                signInfo.setSignLink();
                signInfo.setValidDate();*/

            }
            //接口调用信息
            operateInfo.setConId(createFlowDTO.getContractId());
            operateInfo.setOpType("创建");
            operateInfo.setOpBy(createFlowDTO.getOperatorId());
            operateInfo.setOpTime(new Date());
            operateInfo.setOpRes("成功");
            operateInfo.setErrorMsg("");
            operateInfo.setErrorCode("");
            operateInfo.setReqParams(createFlowDTO.toString());
            operateInfo.setResResults(resp.getFlowIds().toString());
            operateInfo.setNote("调用接口createFlowByTemplate");
            localEsignRecordInfo(operateInfo,contractInfo,signInfo);
           // return Result.ok(("创建签署流程成功，合同ID:"+resp.getFlowIds()[0]));
            return Result.ok((resp.getFlowIds()[0]));
        } catch (TencentCloudSDKException e) {
            //调用本地操作记录表
            TencentOperateInfo  operateInfo=new TencentOperateInfo();
            operateInfo.setConId(createFlowDTO.getContractId());
            operateInfo.setOpType("创建");
            operateInfo.setOpBy(createFlowDTO.getOperatorId());
            operateInfo.setOpTime(new Date());
            operateInfo.setOpRes("失败");
            operateInfo.setErrorMsg(e.getMessage());
            operateInfo.setErrorCode(e.getErrorCode());
            operateInfo.setReqParams(createFlowDTO.toString());
            operateInfo.setResResults("");
            operateInfo.setNote("调用接口createFlowByTemplate");
            localEsignRecordInfo(operateInfo,null,null);
            log.error("腾讯电子签合同创建失败", e);
            return Result.error("腾讯电子签合同创建失败: " + e.getMessage());
        }
    }

    // 构造请求参数
    public  CreateFlowsByTemplatesRequest  buildRequestParams(CreateFlowDTO dto) {
        CreateFlowsByTemplatesRequest req = new CreateFlowsByTemplatesRequest();
        // 设置操作人信息
        UserInfo operator = new UserInfo();
        operator.setOpenId(dto.getOperatorId().toString());
        req.setOperator(operator);
        // 设置代理应用信息（如有）
        if (appId != null) {
            Agent agent = new Agent();
            agent.setAppId(appId);
            agent.setProxyOrganizationOpenId(dto.getProxyOrganizationOpenId());//给子企业起的一个代号，需要自己定义
            agent.setProxyOperator(operator); //子企业员工的个性化标识
            req.setAgent(agent);
        }

        FormField[]  formFields= null;
        //获取控件件信息
        if(dto.getFormFields()!=null&&!dto.getFormFields().isEmpty()){
             formFields= convertFormFields(dto.getFormFields());
        }

        // 3. 设置流程和模板信息
        FlowInfo[] flowInfos = new FlowInfo[1]; // 可以创建多个流程
        FlowInfo flowInfo = new FlowInfo();

        flowInfo.setFormFields(formFields);
        // 流程基本信息
        flowInfo.setFlowName(dto.getFlowName()); // 合同名称
        flowInfo.setFlowDescription(dto.getFlowDescription()); // 合同描述
        flowInfo.setFlowType("合同"); // 流程类型
        flowInfo.setDeadline(System.currentTimeMillis() / 1000 + 7 * 24 * 3600); // 7天后过期
        flowInfo.setTemplateId(dto.getTemplateId());

        // 设置签署参与者
        FlowApproverInfo[] approvers = new FlowApproverInfo[2]; // 两个签署方

        // 第一个签署方（企业方）
        FlowApproverInfo companyApprover = new FlowApproverInfo();
        companyApprover.setApproverType("ORGANIZATION"); // 企业签署方
        companyApprover.setOrganizationName(dto.getProxyOrganizationName());
        companyApprover.setOrganizationOpenId(dto.getProxyOrganizationOpenId());

        companyApprover.setName(dto.getOperatorName());
        companyApprover.setMobile(dto.getOperatorTel());


        // 设置签署控件（需与模板中的控件对应）
        Component[] companyComponents = new Component[1];
        Component signComponent = new Component();
        signComponent.setComponentName("企业印章"); // 控件名称需与模板中一致
        signComponent.setComponentType("SIGN_SIGNATURE"); // 签名控件
        signComponent.setComponentValue(""); // 签名值由签署时填写
        companyComponents[0] = signComponent;
        companyApprover.setSignComponents(companyComponents);

        // 第二个签署方（个人）
        FlowApproverInfo personApprover =new FlowApproverInfo();
        if(dto.getSigners()!=null&&!dto.getSigners().isEmpty()){
             personApprover =convertSigners(dto.getSigners());


        }

        // 设置个人签署控件
        Component[] personComponents = new Component[2];
        Component personSign = new Component();
        personSign.setComponentName("个人签名/印章");
        personSign.setComponentType("SIGN_SIGNATURE");
        personComponents[0] = personSign;

        Component dateComponent = new Component();
        dateComponent.setComponentId("date1");
        dateComponent.setComponentType("DATE");
        dateComponent.setComponentValue(""); // 日期由签署时填写
        personComponents[1] = dateComponent;

        personApprover.setSignComponents(personComponents);

        approvers[0] = companyApprover;
        approvers[1] = personApprover;
        flowInfo.setFlowApprovers(approvers);
        flowInfos[0] = flowInfo;
        req.setFlowInfos(flowInfos);
        return req;
    }

//获取合同表单控件信息
    private   FormField[] convertFormFields(List<CreateFlowDTO.FormField> formFields) {
        FormField  formField1= null;
        int i=0;
        FormField[] fields= new FormField[formFields.size()];
        for (CreateFlowDTO.FormField field : formFields) {
            formField1= new FormField();
            formField1.setComponentName(field.getComponentName());
            formField1.setComponentValue(field.getComponentValue());
            fields[i++] =formField1 ;
        }
        return fields;
    }

    //获取签署人信息
    private  FlowApproverInfo convertSigners(List<CreateFlowDTO.Signer> signers) {

        FlowApproverInfo personApprover = new FlowApproverInfo();
        for (CreateFlowDTO.Signer signer : signers) {
            personApprover.setApproverType(signer.getApproverType()); // 个人签署方
            personApprover.setName(signer.getName());
            personApprover.setMobile(signer.getMobile());
            personApprover.setIdCardNumber(signer.getIdCardNumber());
          //  personApprover.setIdCardType(signer.getIdCardType());
        }
        return personApprover;
    }

    // 初始化客户端
    public EssbasicClient getInitClient() {

        Credential cred = new Credential(secretId, secretKey);

        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(endpoint); // 接口域名 第三方应用集成 联调环境

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        // 实例化一个client
        EssbasicClient client = new EssbasicClient(cred, region, clientProfile);
        return client;

    }



    //调用腾讯电子签查询模板信息列表接口
    @Override
   public Result<List<TemplateInfoDTO>> getDescribeTemplates(CreateFlowDTO createFlowDTO){
        try {
            // 1.初始化客户端
            // 实例化一个client
            EssbasicClient client = getInitClient();

            // 2. 构建请求参数
            DescribeTemplatesRequest req = new DescribeTemplatesRequest();
            // 设置操作人信息
            UserInfo userInfo = new UserInfo();
            userInfo.setOpenId(createFlowDTO.getOperatorId());
            req.setOperator(userInfo);
            if (appId != null) {
                Agent agent = new Agent();
                agent.setAppId(appId);
                agent.setProxyOrganizationOpenId(createFlowDTO.getProxyOrganizationOpenId());//给子企业起的一个代号，需要自己定义
                agent.setProxyOperator(userInfo); //子企业员工的个性化标识
                req.setAgent(agent);
            }

            // 可选查询条件（根据需要设置）

            if(createFlowDTO.getTemplateId()!=null&&!createFlowDTO.getTemplateId().isEmpty()){
                req.setTemplateId(createFlowDTO.getTemplateId()); // 模板ID，不填则查询所有
            }

            // 3. 发送请求并获取响应
            DescribeTemplatesResponse resp = client.DescribeTemplates(req);
            // 4. 处理响应结果
          //  System.out.println("请求成功，响应数据:");
         //   System.out.println(DescribeTemplatesResponse.toJsonString(resp));

            // 打印模板列表
        /*    if (resp.getTemplates() != null) {
                System.out.println("\n模板列表:");
                for (TemplateInfo template : resp.getTemplates()) {
                    System.out.println("----------------------------");
                    System.out.println("模板ID: " + template.getTemplateId());
                    System.out.println("模板名称: " + template.getTemplateName());
                    System.out.println("模板描述: " + template.getDescription());
                    System.out.println("创建时间: " + template.getCreatedOn());
                    System.out.println("预览URL: " + template.getPreviewUrl());
                    System.out.println("RecipientId: " + template.getRecipients());
                    System.out.println("模板控件数量: " + template.getComponents().length);
                    System.out.println("模板RecipientId数量: " + template.getRecipients().length);
                    // 打印签署方RecipientId
                    System.out.println("RecipientId列表:");
                    Arrays.stream(template.getRecipients())
                            .forEach(recipient -> {
                                System.out.println("  - 控件ID: " + recipient.getRecipientId() +
                                        ", 类型: " +recipient.getRecipientType() +
                                        ", 角色: " + recipient.getRoleName());
                            });
                    // 打印模板控件信息
                    System.out.println("控件列表:");
                    Arrays.stream(template.getComponents())
                            .forEach(component -> {
                                System.out.println("  - 控件ID: " + component.getComponentId() +
                                        ", 类型: " + component.getComponentType() +
                                        ", 名称: " + component.getComponentName());
                            });
                }
            }*/
            // 模板列表坐位返回对象
            List<TemplateInfoDTO> temList = new ArrayList();
            if (resp.getTemplates() != null) {
                for (TemplateInfo template : resp.getTemplates()) {
                    TemplateInfoDTO tem = new TemplateInfoDTO();
                    tem.setTemplateId(template.getTemplateId());
                    tem.setTemplateName(template.getTemplateName());
                    tem.setDescription(template.getDescription());

                    List<TemplateInfoDTO.Components> comList = new ArrayList();
                    Arrays.stream(template.getComponents())
                            .forEach(component -> {
                                TemplateInfoDTO.Components  com = new TemplateInfoDTO.Components();
                                com.setComponentName(component.getComponentName());
                                com.setComponentValue(component.getComponentValue());
                                comList.add(com);

                            });
                    tem.setComponents(comList);
                    List<TemplateInfoDTO.Recipients> recipientsList = new ArrayList();
                    Arrays.stream(template.getRecipients())
                            .forEach(recipient -> {
                                TemplateInfoDTO.Recipients  com = new TemplateInfoDTO.Recipients();
                                com.setRecipientId(recipient.getRecipientId());
                                com.setRecipientType(recipient.getRecipientType());
                                com.setRoleName(recipient.getRoleName());
                                recipientsList.add(com);

                            });
                    tem.setRecipients(recipientsList);
                    temList.add(tem);
                }
            }
            //调用本地操作记录表
            TencentOperateInfo  operateInfo=new TencentOperateInfo();
            operateInfo.setConId(createFlowDTO.getContractId());
            operateInfo.setOpType("查询");
            operateInfo.setOpBy(createFlowDTO.getOperatorId());
            operateInfo.setOpTime(new Date());
            operateInfo.setOpRes("成功");
            operateInfo.setErrorMsg("");
            operateInfo.setErrorCode("");
            operateInfo.setReqParams(createFlowDTO.toString());
            operateInfo.setResResults(resp.getTemplates().toString());
            operateInfo.setNote("调用接口getDescribeTemplate");
            localEsignRecordInfo(operateInfo,null,null);


            return Result.OK("查询成功",temList);
        } catch (TencentCloudSDKException e) {
            //调用本地操作记录表
            TencentOperateInfo  operateInfo=new TencentOperateInfo();
            operateInfo.setConId(createFlowDTO.getContractId());
            operateInfo.setOpType("查询");
            operateInfo.setOpBy(createFlowDTO.getOperatorId());
            operateInfo.setOpTime(new Date());
            operateInfo.setOpRes("失败");
            operateInfo.setErrorMsg(e.getMessage());
            operateInfo.setErrorCode(e.getErrorCode());
            operateInfo.setReqParams(createFlowDTO.toString());
            operateInfo.setResResults("");
            operateInfo.setNote("调用接口getDescribeTemplate");
            localEsignRecordInfo(operateInfo,null,null);
            log.error("调用接口getDescribeTemplate查询失败", e);
            return  Result.OK("查询失败！"+e.getMessage(),null);
        }

    }


    // 生成子客登录链接接口
    @Override
  public   Result<String> getCreateConsoleLoginUrl(CreateFlowDTO createFlowDTO)  {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String createBy = loginUser != null ? loginUser.getUsername() : "system";

        // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
        // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
        // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
        try {
           // 1. 初始化客户端
            EssbasicClient client = getInitClient();
            // 实例化一个请求对象,每个接口都会对应一个request对象
            CreateConsoleLoginUrlRequest req = new CreateConsoleLoginUrlRequest();
            // 设置操作人信息
            UserInfo operator = new UserInfo();
            operator.setOpenId(createFlowDTO.getOperatorId());
            req.setOperator(operator);
            // 设置代理应用信息（如有）
            if (appId != null) {
                Agent agent = new Agent();
                agent.setAppId(appId.toString());
                agent.setProxyOrganizationOpenId(createFlowDTO.getProxyOrganizationOpenId());//给子企业起的一个代号，需要自己定义
                agent.setProxyOperator(operator); //子企业员工的个性化标识
                req.setAgent(agent);
            }

            //指定加入应用的子企业的名称
            req.setProxyOrganizationName(createFlowDTO.getProxyOrganizationName());
            //子企业员工姓名
            req.setProxyOperatorName(createFlowDTO.getOperatorName());
            //子企业员工联系电话
            req.setProxyOperatorMobile(createFlowDTO.getOperatorTel());

            // 返回的resp是一个CreateConsoleLoginUrlResponse的实例，与请求对象对应
            CreateConsoleLoginUrlResponse resp = client.CreateConsoleLoginUrl(req);
            // 输出json格式的字符串回包
            System.out.println(CreateConsoleLoginUrlResponse.toJsonString(resp));

            //调用本地操作记录表
            TencentOperateInfo  operateInfo=new TencentOperateInfo();
            operateInfo.setConId(createFlowDTO.getContractId());
            operateInfo.setOpType("创建");
            operateInfo.setOpBy(createFlowDTO.getOperatorId());
            operateInfo.setOpTime(new Date());
            operateInfo.setOpRes("成功");
            operateInfo.setErrorMsg("");
            operateInfo.setErrorCode("");
            operateInfo.setReqParams(createFlowDTO.toString());
            operateInfo.setResResults(CreateConsoleLoginUrlResponse.toJsonString(resp));
            operateInfo.setNote("调用接口getCreateConsoleLoginUrl");
            localEsignRecordInfo(operateInfo,null,null);
            ProxyOrganizationName = createFlowDTO.getProxyOrganizationName();
            Mobile = createFlowDTO.getOperatorTel();
            //将生成的子客登录数据存入本地数据库表
            TencentConsoleloginurlInfo tencentConsoleloginurlInfo=new TencentConsoleloginurlInfo();
            tencentConsoleloginurlInfo.setProxyorganizationopenid(createFlowDTO.getProxyOrganizationOpenId());
            tencentConsoleloginurlInfo.setProxyorganizationname(createFlowDTO.getProxyOrganizationName());
            tencentConsoleloginurlInfo.setOperatorid(createFlowDTO.getOperatorId());
            tencentConsoleloginurlInfo.setOperatorname(createFlowDTO.getOperatorName());
            tencentConsoleloginurlInfo.setOperatortel(createFlowDTO.getOperatorTel());
            tencentConsoleloginurlInfo.setResultMsg(resp.getConsoleUrl());
            tencentConsoleloginurlInfo.setCreateBy(createBy);
            tencentConsoleloginurlInfoService.save(tencentConsoleloginurlInfo);


            return Result.OK("腾讯电子签子客企业认证链接生成成功！", resp.getConsoleUrl());
        }catch (TencentCloudSDKException e){
            //调用本地操作记录表
            TencentOperateInfo  operateInfo=new TencentOperateInfo();
            operateInfo.setConId(createFlowDTO.getContractId());
            operateInfo.setOpType("创建");
            operateInfo.setOpBy(createFlowDTO.getOperatorId());
            operateInfo.setOpTime(new Date());
            operateInfo.setOpRes("失败");
            operateInfo.setErrorMsg(e.getErrorCode());
            operateInfo.setErrorCode(e.getMessage());
            operateInfo.setReqParams(createFlowDTO.toString());
            operateInfo.setResResults("");
            operateInfo.setNote("调用接口getCreateConsoleLoginUrl");
            localEsignRecordInfo(operateInfo,null,null);

            log.error("腾讯电子签子客企业认证链接生成失败", e);
            return Result.error("腾讯电子签子客企业认证链接生成失败: " + e.getMessage());
        }
    }
    //给个人/自然人生成签署链接
    @Override
    public  Result<String>  createPersonSignLink(CreateFlowDTO dto){
        try{
            //1.初始化客户端
            EssbasicClient client = getInitClient();
            // 2. 构造创建小程序链接请求
            CreateSignUrlsRequest req = new CreateSignUrlsRequest();
            // 3. 设置请求参数
            // 设置操作人信息
            UserInfo operator = new UserInfo();
            operator.setOpenId(dto.getOperatorId());
            req.setOperator(operator);
            // 设置代理应用信息（如有）
            if (appId != null) {
                Agent agent = new Agent();
                agent.setAppId(appId.toString());
                agent.setProxyOrganizationOpenId(dto.getProxyOrganizationOpenId());//给子企业起的一个代号，需要自己定义
                agent.setProxyOperator(operator); //子企业员工的个性化标识
                req.setAgent(agent);
            }

            // 设置合同信息
            req.setFlowIds(new String[]{dto.getContractId()});
            // 设置签署人类型
            req.setGenerateType(Config.GenerateType);
            // 链接类型：小程序
            req.setEndpoint(Config.Endpoint);
            // 设置签署人
            FlowApproverInfo personApprover = convertSigners(dto.getSigners());
            req.setName(personApprover.getName());
            req.setMobile(personApprover.getMobile());
            System.out.println("腾讯电子签接口现在开始触发回调");
            // 4. 调用API
            CreateSignUrlsResponse response = client.CreateSignUrls(req);
            String url = "";
            // 5. 返回小程序链接
            for (SignUrlInfo signUrlInfo :  response.getSignUrlInfos()) {
                url = signUrlInfo.getSignUrl();
            }
            //调用本地操作记录表
            TencentOperateInfo  operateInfo=new TencentOperateInfo();
            operateInfo.setConId(dto.getContractId());
            operateInfo.setOpType("创建");
            operateInfo.setOpBy(dto.getOperatorId());
            operateInfo.setOpTime(new Date());
            operateInfo.setOpRes("成功");
            operateInfo.setErrorMsg("");
            operateInfo.setErrorCode("");
            operateInfo.setReqParams(dto.toString());
            operateInfo.setResResults(CreateSignUrlsResponse.toJsonString(response));
            operateInfo.setNote("调用接口createPersonSignLink");
            localEsignRecordInfo(operateInfo,null,null);

            return Result.OK("腾讯电子签小程序签署链接生成成功！",url);
        }catch (TencentCloudSDKException e){
            //调用本地操作记录表
            TencentOperateInfo  operateInfo=new TencentOperateInfo();
            operateInfo.setConId(dto.getContractId());
            operateInfo.setOpType("创建");
            operateInfo.setOpBy(dto.getOperatorId());
            operateInfo.setOpTime(new Date());
            operateInfo.setOpRes("失败");
            operateInfo.setErrorMsg( e.getMessage());
            operateInfo.setErrorCode(e.getErrorCode());
            operateInfo.setReqParams(dto.toString());
            operateInfo.setResResults("");
            operateInfo.setNote("调用接口createPersonSignLink");
            localEsignRecordInfo(operateInfo,null,null);
            log.error("腾讯电子签小程序签署链接生成失败", e);
            return Result.error("腾讯电子签小程序签署链接生成失败: " + e.getMessage());
        }

    }

    @Autowired
    private ITencentOperateInfoService tencentOperateInfoService;
    @Autowired
    private ITencentSignInfoService tencentSignInfoService;
    @Autowired
    private ITencentFlowstatuscallbackInfoService tencentFlowstatuscallbackInfoService;
    @Autowired
    private ITencentForwardflowcallbackInfoService tencentForwardflowcallbackInfoService;
    @Autowired
    private INurseHospitalService nurseHospitalService;
    @Autowired
    private ITencentStaffcallbackInfoService tencentStaffcallbackInfoService;
    @Autowired
    private ITencentConsoleloginurlInfoService tencentConsoleloginurlInfoService;
    @Autowired
    private HealthRecordInfoController healthRecordInfoController;
    @Autowired
    private AssessSpecialInfoController assessSpecialInfoController;

    //本地记录合同签署信息和操作记录
    public void  localEsignRecordInfo(TencentOperateInfo  operateInfo,TencentContractInfo contractInfo, TencentSignInfo signInfo){
        //接口调用日志表 tencent_operate_info
        tencentOperateInfoService.save(operateInfo);
        //签署方信息表 tencent_sign_info
        if(signInfo!=null){
            tencentSignInfoService.save(signInfo);
        }
        //合同记录表 tencent_contract_info
        if(contractInfo!=null){
            this.save(contractInfo);
        }

    }
    public static byte[] pkcs7Padding(byte[] ciphertext, int blockSize) {
        int padding = blockSize - ciphertext.length % blockSize;
        byte[] padtext = repeat((byte) padding, padding);
        ciphertext = append(ciphertext, padtext);
        return ciphertext;
    }

    public static byte[] repeat(byte val, int count) {
        byte[] result = new byte[count];
        for (int i = 0; i < count; i++) {
            result[i] = val;
        }
        return result;
    }

    public static byte[] append(byte[] a, byte[] b) {
        byte[] result = new byte[a.length + b.length];
        System.arraycopy(a, 0, result, 0, a.length);
        System.arraycopy(b, 0, result, a.length, b.length);
        return result;
    }

    public static byte[] pkcs7UnPadding(byte[] origData) {
        int length = origData.length;
        int unpadding = origData[length - 1];
        byte[] result = new byte[length - unpadding];
        System.arraycopy(origData, 0, result, 0, result.length);
        return result;
    }
//加密
    public static byte[] aesEncrypt(byte[] origData, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        int blockSize = cipher.getBlockSize();
        origData = pkcs7Padding(origData, blockSize);
        SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
        byte[] iv = new byte[blockSize];
        System.arraycopy(key, 0, iv, 0, iv.length);
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
        byte[] encrypted = cipher.doFinal(origData);
        return Base64.getEncoder().encode(encrypted);
    }
//解密
    public static byte[] aesDecrypt(byte[] crypted, byte[] key) throws Exception {
        byte[] decoded = Base64.getDecoder().decode(crypted);
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        int blockSize = cipher.getBlockSize();
        SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
        byte[] iv = new byte[blockSize];
        System.arraycopy(key, 0, iv, 0, iv.length);
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
        byte[] origData = cipher.doFinal(decoded);
        return pkcs7UnPadding(origData);
    }
    //正式的回调URL
    @Override
    public Result<String>  handleCallback(HttpServletRequest request, String body) throws Exception {
        //1、接收数据&json_code 2、base64解码 3、aes解密
        // 传入CallbackUrlKey
        byte[] key = keyCallBack.getBytes();
        // 传入密文,如果接收到的数据是{"encrypt":"base64后的密文"},需要提取出encrypt的值base64后的密文
        JsonObject json = JsonParser.parseString(body).getAsJsonObject();
        String value = json.get("encrypt").getAsString();  // 提取键为'encrypt'的值
        byte[] origData = aesDecrypt(value.getBytes(StandardCharsets.UTF_8), key);
        // 打印解密后的内容，格式为json
      //  System.out.println("解密后"+new String(origData, StandardCharsets.UTF_8));
        String strDecrypt = new String(origData, StandardCharsets.UTF_8);

        JsonObject jsonDecrypt = JsonParser.parseString(strDecrypt).getAsJsonObject();

        //处理合同签署回调
        if("FlowStatusChange".equals(jsonDecrypt.get("MsgType").toString().replace("\"",""))){
            //合同状态变动通知
            doFlowStatusChange(strDecrypt);
        }else if("ForwardFLow".equals(jsonDecrypt.get("MsgType").toString().replace("\"",""))){
            //合同转交签署任务
            doForwardFLow(strDecrypt);
        }else if("VerifyStaffInfo".equals(jsonDecrypt.get("MsgType").toString().replace("\"",""))){
            //员工加入企业通知
         //   doVerifyStaffInfo(strDecrypt);
        }else if("QuiteJob".equals(jsonDecrypt.get("MsgType").toString().replace("\"",""))){
            //员工离职回调通知
            doQuiteJob(strDecrypt);
        }

        return Result.OK("回调成功");
    }

//合同相关回调-- 回调消息类型FlowStatusChange

    private void  doFlowStatusChange(String strDecrypt) throws JsonProcessingException {
        JsonObject jsonDecrypt = JsonParser.parseString(strDecrypt).getAsJsonObject();
        JsonObject jsonMsgData = jsonDecrypt.get("MsgData").getAsJsonObject();
        String strMsgData = String.valueOf(jsonDecrypt.get("MsgData"));
        JsonArray jsonFlowApproverInfo = jsonMsgData.get("FlowApproverInfo").getAsJsonArray();
        String strFlowApproverInfo = String.valueOf(jsonMsgData.get("FlowApproverInfo"));

        List<JsonObject> listFlowApproverInfo=new ArrayList<>();
        for(int i=0;i<jsonFlowApproverInfo.size();i++){
            listFlowApproverInfo.add((JsonObject) jsonFlowApproverInfo.get(i));
        }
        // 2. 解析回调数据
        TencentFlowstatuscallbackInfo callbackInfo =new TencentFlowstatuscallbackInfo();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        TencentFlowstatuscallbackDTO callback = objectMapper.readValue(strDecrypt,TencentFlowstatuscallbackDTO.class);
        TencentFlowstatuscallbackDTO.MsgData msgDataInfo = objectMapper.readValue(strMsgData,TencentFlowstatuscallbackDTO.MsgData.class);
        int i =0;
        for (JsonObject  jsonObj : listFlowApproverInfo) {
             //如果机构信息id是空的，说明是个人签署方
            if("".equals(jsonObj.get("ProxyOrganizationOpenId").toString().replace("\"", ""))) {
                //第一个签署方保存的是个人签署方的信息
                callbackInfo.setApprovemessagea(jsonObj.get("ApproveMessage").toString().replace("\"", ""));
                callbackInfo.setApprovenamea(jsonObj.get("ApproveName").toString().replace("\"", ""));
                callbackInfo.setApprovestatusa(jsonObj.get("ApproveStatus").toString().replace("\"", ""));

                String approveTime = jsonObj.get("ApproveTime").toString().replace("\"", "");
                int approveDate = Integer.parseInt(approveTime);
                callbackInfo.setApprovetimea(new Date(approveDate));

                String approverDeadline = jsonObj.get("ApproverDeadline").toString().replace("\"", "");
                int deadline = Integer.parseInt(approverDeadline);
                callbackInfo.setApproverdeadlinea(new Date(deadline));
                callbackInfo.setCasigna(jsonObj.get("CaSign").toString().replace("\"", ""));
                callbackInfo.setOrganizationnamea(jsonObj.get("OrganizationName").toString().replace("\"", ""));
                callbackInfo.setPhonenumbera(jsonObj.get("PhoneNumber").toString().replace("\"", ""));
                callbackInfo.setProxyoperatoropenida(jsonObj.get("ProxyOperatorOpenId").toString().replace("\"", ""));
                callbackInfo.setProxyorganizationnamea(jsonObj.get("ProxyOrganizationName").toString().replace("\"", ""));
                callbackInfo.setProxyorganizationopenida(jsonObj.get("ProxyOrganizationOpenId").toString().replace("\"", ""));
                callbackInfo.setRecipientida(jsonObj.get("RecipientId").toString().replace("\"", ""));
                callbackInfo.setSignordera(jsonObj.get("SignOrder").toString().replace("\"", ""));

                i++;
            }else{
                //第一个签署方保存的是企业签署方的信息
                callbackInfo.setApprovemessageb(jsonObj.get("ApproveMessage").toString().replace("\"", ""));
                callbackInfo.setApprovenameb(jsonObj.get("ApproveName").toString().replace("\"", ""));
                callbackInfo.setApprovestatusb(jsonObj.get("ApproveStatus").toString().replace("\"", ""));

                String approveTime = jsonObj.get("ApproveTime").toString().replace("\"", "");
                int approveDate = Integer.parseInt(approveTime);
                callbackInfo.setApprovetimeb(new Date(approveDate));

                String approverDeadline = jsonObj.get("ApproverDeadline").toString().replace("\"", "");
                int deadline = Integer.parseInt(approverDeadline);
                callbackInfo.setApproverdeadlineb(new Date(deadline));
                callbackInfo.setCasignb(jsonObj.get("CaSign").toString().replace("\"", ""));
                callbackInfo.setOrganizationnameb(jsonObj.get("OrganizationName").toString().replace("\"", ""));
                callbackInfo.setPhonenumberb(jsonObj.get("PhoneNumber").toString().replace("\"", ""));
                callbackInfo.setProxyoperatoropenidb(jsonObj.get("ProxyOperatorOpenId").toString().replace("\"", ""));
                callbackInfo.setProxyorganizationnameb(jsonObj.get("ProxyOrganizationName").toString().replace("\"", ""));
                callbackInfo.setProxyorganizationopenidb(jsonObj.get("ProxyOrganizationOpenId").toString().replace("\"", ""));
                callbackInfo.setRecipientidb(jsonObj.get("RecipientId").toString().replace("\"", ""));
                callbackInfo.setSignorderb(jsonObj.get("SignOrder").toString().replace("\"", ""));

            }
        }

        //  TencentFlowstatuscallbackDTO.FlowApproverInfo flowApprovers = objectMapper.readValue(strFlowApproverInfo,TencentFlowstatuscallbackDTO.FlowApproverInfo.class);

        callbackInfo.setMsgid(callback.getMsgid());
        callbackInfo.setMsgtype(callback.getMsgtype());
        callbackInfo.setMsgversion(callback.getMsgversion());
        callbackInfo.setApplicationid(msgDataInfo.getApplicationid());
        callbackInfo.setCcinfo(msgDataInfo.getCcinfo());
        callbackInfo.setCreateon(new Date((long)msgDataInfo.getCreateon()*1000));
        callbackInfo.setCustomerdata(msgDataInfo.getCustomerdata());
        callbackInfo.setDeadline(new Date((long)msgDataInfo.getDeadline()*1000));

        callbackInfo.setFlowid(msgDataInfo.getFlowid());
        callbackInfo.setFlowmessage(msgDataInfo.getFlowmessage());
        callbackInfo.setFlowname(msgDataInfo.getFlowname());
        callbackInfo.setFlowstatus(msgDataInfo.getFlowstatus());
        callbackInfo.setFlowtype(msgDataInfo.getFlowtype());
        callbackInfo.setOccurtime(new Date((long)msgDataInfo.getOccurtime()*1000));
        callbackInfo.setProxyoperatoropenid(msgDataInfo.getProxyoperatoropenid());
        callbackInfo.setProxyorganizationopenid(msgDataInfo.getProxyorganizationopenid());
        callbackInfo.setReleaseflowid(msgDataInfo.getReleaseflowid());
        callbackInfo.setTemplateid(msgDataInfo.getTemplateid());

        System.out.println("doFlowStatusChange-callbackInfo:" + callbackInfo.toString());

        //保存回调数据
        tencentFlowstatuscallbackInfoService.save(callbackInfo);
//如果合同签署完成则通过姓名更新nurse_user 表的is_verify字段为1
        //2025.8.12 新增--合同签署完成后往健康档案--个人人口学基本信息表的新增接口里新增一条用户基础信息，包括姓名、电话、同时生成健康档案编号
        //2025.9.13 新增--合同签署完成后往全面评估的专科评估信息表--添加个人用户基础信息，包括姓名、电话
        if("ALL".equals(msgDataInfo.getFlowstatus())){
            //腾讯没返回身份证，我用的身份证全局变量到回调那一步已经被重置为空了,故不能根据身份证更新
            //1、如果合同签署完成则通过姓名 更新nurse_user 表的is_verify字段为1
            System.out.println("更新的用户姓名：" + callbackInfo.getApprovenamea());
            tencentContractInfoMapper.updateNurseUser1(callbackInfo.getApprovenamea(),callbackInfo.getPhonenumbera());
            //2、如果合同签署完成则通过姓名，手机 修改nurse_user_family 表is_verify字段为1
            tencentContractInfoMapper.updateNurseUserFamily(callbackInfo.getApprovenamea(),callbackInfo.getPhonenumbera());
           List<NurseUser> nurseUserList = nurseUserService.list(new QueryWrapper<NurseUser>().eq("name",callbackInfo.getApprovenamea()).eq("phone",callbackInfo.getPhonenumbera()));
           String id_number="";
           if(oConvertUtils.isNotEmpty(nurseUserList) && !nurseUserList.isEmpty()) {
               id_number = nurseUserList.get(0).getIdcard();
           }
           //2025.8.12 新增--2、合同签署完成后往健康档案--个人人口学基本信息表的新增接口里新增一条用户基础信息，包括姓名、电话、身份证，同时生成健康档案编号
            HealthRecordInfo healthRecordInfo = new HealthRecordInfo();
            healthRecordInfo.setName(callbackInfo.getApprovenamea());//个人签署方姓名
            healthRecordInfo.setTel(callbackInfo.getPhonenumbera());
            healthRecordInfo.setIdNumber(id_number);
            healthRecordInfo.setValid(1);
            healthRecordInfo.setCreateBy("admin");
            //验证健康档案里是否存在该服务对象的信息，存在则health_record_demology表不插入数据,不存在则插入数据
            Result<List<HealthRecordInfo>> list=healthRecordInfoController.queryByRecordId(healthRecordInfo);
            if(list.isSuccess()){
               if( list.getResult().size()==0){
                   healthRecordInfoController.add(healthRecordInfo);
               }
            }
            //2025.9.13 新增--合同签署完成后往全面评估的专科评估信息表--添加个人用户基础信息，包括姓名、电话
            //验证全面评估的专科评估信息表是否存在该服务对象的信息，存在则 assess_Special_Info 表不插入数据,不存在则插入数据
            AssessSpecialInfo assessSpecialInfo =new AssessSpecialInfo();
            assessSpecialInfo.setName(callbackInfo.getApprovenamea());
            assessSpecialInfo.setTel(callbackInfo.getPhonenumbera());
            assessSpecialInfo.setAssessid(String.valueOf(0));
            assessSpecialInfo.setValid(1);
            assessSpecialInfo.setCreateBy("admin");
            Result<List<AssessSpecialInfo>> listAssess=assessSpecialInfoController.queryByOther(assessSpecialInfo);
            if(listAssess.isSuccess()){
                if( listAssess.getResult().size()==0){
                    assessSpecialInfoController.add(assessSpecialInfo).getResult();
                    assessSpecialInfo.setAssessid(assessSpecialInfo.getId());
                    assessSpecialInfoController.edit(assessSpecialInfo);
                }
            }
            //3、合同签署完成后下载合同文件保存到本地目录(前提需要超级管理员（一般为企业法人）在子客企业后台开通下载合同权限)
      if(downloadEnabled){
          tencentFlowsFileService.downloadSignedContract(callbackInfo.getFlowid(),callbackInfo.getFlowname(),callbackInfo.getProxyoperatoropenid(),callbackInfo.getProxyorganizationopenid());
      }

        }
    }



    //合同相关回调-- 转交签署任务 ForwardFLow
    private void  doForwardFLow(String strDecrypt) throws JsonProcessingException {
        JsonObject jsonDecrypt = JsonParser.parseString(strDecrypt).getAsJsonObject();
        JsonObject jsonMsgData = jsonDecrypt.get("MsgData").getAsJsonObject();
        String strMsgData = String.valueOf(jsonDecrypt.get("MsgData"));

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        TencentForwardflowcallbackInfo callback = objectMapper.readValue(strDecrypt, TencentForwardflowcallbackInfo.class);
        TencentForwardflowcallbackInfo.MsgData msgDataInfo = objectMapper.readValue(strMsgData,TencentForwardflowcallbackInfo.MsgData.class);
        callback.setApplicationid(msgDataInfo.getApplicationid());
        callback.setProxyoperatoropenid(msgDataInfo.getProxyoperatoropenid());
        callback.setProxyorganizationopenid(msgDataInfo.getProxyorganizationopenid());
        callback.setFlowid(msgDataInfo.getFlowid());
        callback.setForwardedopenid(msgDataInfo.getForwardedopenid());
        tencentForwardflowcallbackInfoService.save(callback);

    }

   /* 员工加入企业通知
1. 回调触发时机 员工加入子客的时候发送此通知
2. 回调消息类型 VerifyStaffInfo
    员工离职回调通知
1. 回调触发时机 员工离职，调用接口SyncProxyOrganizationOperators（同步企业员工）
2. 回调消息类型 QuiteJob*/
    //员工加入企业通知
   private void  doVerifyStaffInfo(String strDecrypt) throws JsonProcessingException {
       JsonObject jsonDecrypt = JsonParser.parseString(strDecrypt).getAsJsonObject();
       String strMsgData = String.valueOf(jsonDecrypt.get("MsgData"));
       ObjectMapper objectMapper = new ObjectMapper();
       objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
       TencentStaffcallbackDTO callback = objectMapper.readValue(strDecrypt, TencentStaffcallbackDTO.class);
       TencentStaffcallbackDTO.MsgData msgDataInfo = objectMapper.readValue(strMsgData,TencentStaffcallbackDTO.MsgData.class);
       TencentStaffcallbackInfo staffcallbackInfo = new TencentStaffcallbackInfo();
       staffcallbackInfo.setMsgid(callback.getMsgid());
       staffcallbackInfo.setMsgtype(callback.getMsgtype());
       staffcallbackInfo.setMsgversion(callback.getMsgversion());
       staffcallbackInfo.setApplicationid(msgDataInfo.getApplicationid());
       staffcallbackInfo.setProxyorganizationopenid(msgDataInfo.getProxyorganizationopenid());
       staffcallbackInfo.setProxyoperatoropenid(msgDataInfo.getProxyoperatoropenid());
       staffcallbackInfo.setOpenid(msgDataInfo.getProxyoperatoropenid());
       staffcallbackInfo.setName(msgDataInfo.getEmployeename());
       //根据腾讯电子签返回参数说明，员工手机号为打码状态，故此处的手机号要使用生成登录链接传入的手机号
      // staffcallbackInfo.setMobile(msgDataInfo.getEmployeemobile());
       staffcallbackInfo.setMobile(Mobile);
      /* staffcallbackInfo.setFromScene();
       staffcallbackInfo.setFailreason();
       staffcallbackInfo.setFailmessage();*/
       staffcallbackInfo.setOperatetime(new Date());

       tencentStaffcallbackInfoService.save(staffcallbackInfo);
       //更新机构表的腾讯电子签子客企业和默认经办人信息
       NurseHospital nurseHospital = new NurseHospital();
       nurseHospital.setProxyorganizationopenid(msgDataInfo.getProxyorganizationopenid());
       nurseHospital.setProxyorganizationname(ProxyOrganizationName);
       nurseHospital.setOperatorid(msgDataInfo.getProxyoperatoropenid());
       nurseHospital.setOperatorname(msgDataInfo.getEmployeename());
       nurseHospital.setOperatortel(msgDataInfo.getEmployeemobile());
       nurseHospital.setUpdateTencentTime(new Date());
       tencentContractInfoMapper.updateHosTencentInfo(ProxyOrganizationName,
               msgDataInfo.getProxyorganizationopenid(),
               msgDataInfo.getProxyoperatoropenid(),
               msgDataInfo.getEmployeename(),
               msgDataInfo.getEmployeemobile()
               );


   }
//员工离职回调通知
    private void  doQuiteJob(String strDecrypt) throws JsonProcessingException {
        JsonObject jsonDecrypt = JsonParser.parseString(strDecrypt).getAsJsonObject();
        String strMsgData = String.valueOf(jsonDecrypt.get("MsgData"));

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        TencentStaffcallbackDTO callback = objectMapper.readValue(strDecrypt, TencentStaffcallbackDTO.class);
        TencentStaffcallbackDTO.MsgData msgDataInfo = objectMapper.readValue(strMsgData,TencentStaffcallbackDTO.MsgData.class);
        TencentStaffcallbackInfo staffcallbackInfo = new TencentStaffcallbackInfo();
        staffcallbackInfo.setMsgid(callback.getMsgid());
        staffcallbackInfo.setMsgtype(callback.getMsgtype());
        staffcallbackInfo.setMsgversion(callback.getMsgversion());
        staffcallbackInfo.setApplicationid(msgDataInfo.getApplicationid());
        staffcallbackInfo.setProxyorganizationopenid(msgDataInfo.getProxyorganizationopenid());
        staffcallbackInfo.setProxyoperatoropenid(msgDataInfo.getProxyoperatoropenid());
        staffcallbackInfo.setOpenid(msgDataInfo.getProxyoperatoropenid());
        //根据腾讯电子签返回参数说明，员工姓名、手机号为打码状态
        staffcallbackInfo.setName(msgDataInfo.getName());
        staffcallbackInfo.setMobile(msgDataInfo.getMobile());
      //  staffcallbackInfo.setFromScene(msgDataInfo.getFrom());
     //  staffcallbackInfo.setFailreason(msgDataInfo.getFailreason());
      //  staffcallbackInfo.setFailmessage(msgDataInfo.getFailmessage());
        staffcallbackInfo.setOperatetime(new Date(msgDataInfo.getOperatetime()));
        tencentStaffcallbackInfoService.save(staffcallbackInfo);
        //查询机构当前默认经办人是否为离职的人员，是则要清除经办人信息
        List<NurseHospital> list = tencentContractInfoMapper.selectHosByName(ProxyOrganizationName);
        if(list.size()>0){
            for(NurseHospital nurseHospital:list){
               if( msgDataInfo.getProxyoperatoropenid().equals(nurseHospital.getOperatorid())){
                   nurseHospital.setOperatorid("");
                   nurseHospital.setOperatorname("");
                   nurseHospital.setOperatortel("");
                   nurseHospital.setUpdateTencentTime(new Date());
                   nurseHospitalService.updateById(nurseHospital);

               }
            }
        }
    }



}
